<script setup>
import { ref, watch, onMounted } from "vue";
import {
  queryStudentPageApi,
  addStudentApi,
  queryStudentByIdApi,
  updateStudentApi,
  deleteStudentApi,
} from "@/api/student";
import { queryClazzAllApi } from "@/api/clazz";
import { ElMessage, ElMessageBox } from "element-plus";

// 性别、学历下拉
const genders = [
  { name: "男", value: 1 },
  { name: "女", value: 2 },
];
const degrees = [
  { name: "初中", value: 1 },
  { name: "高中", value: 2 },
  { name: "大专", value: 3 },
  { name: "本科", value: 4 },
  { name: "硕士", value: 5 },
  { name: "博士", value: 6 },
];
const isCollegeOptions = [
  { name: "是", value: 1 },
  { name: "否", value: 0 },
];

// 班级下拉
const clazzList = ref([]);
const fetchClazzList = async () => {
  const res = await queryClazzAllApi();
  if (res.code) {
    clazzList.value = res.data;
  }
};

// 查询表单
const searchForm = ref({ name: "", no: "", gender: "", clazzId: "", phone: "" });

// 学员列表、分页
const studentList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const fetchStudentList = async () => {
  const params = {
    name: searchForm.value.name,
    no: searchForm.value.no,
    gender: searchForm.value.gender,
    clazzId: searchForm.value.clazzId,
    phone: searchForm.value.phone,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  const res = await queryStudentPageApi(params);
  if (res.code) {
    studentList.value = res.data.records || res.data.list || [];
    total.value = res.data.total;
  }
};

onMounted(() => {
  fetchStudentList();
  fetchClazzList();
});

const handleSizeChange = () => fetchStudentList();
const handleCurrentChange = () => fetchStudentList();
const clear = () => {
  searchForm.value = { name: "", no: "", gender: "", clazzId: "", phone: "" };
  fetchStudentList();
};

// 弹窗表单
const dialogVisible = ref(false);
const dialogTitle = ref("新增学员");
const studentForm = ref({
  name: "",
  no: "",
  gender: "",
  phone: "",
  idCard: "",
  isCollege: "",
  address: "",
  degree: "",
  graduationDate: "",
  clazzId: "",
});
const studentFormRef = ref();

const openAdd = () => {
  dialogTitle.value = "新增学员";
  dialogVisible.value = true;
  studentForm.value = {
    name: "",
    no: "",
    gender: "",
    phone: "",
    idCard: "",
    isCollege: "",
    address: "",
    degree: "",
    graduationDate: "",
    clazzId: "",
  };
  if (studentFormRef.value) studentFormRef.value.resetFields();
};

const openEdit = async (row) => {
  dialogTitle.value = "编辑学员";
  dialogVisible.value = true;
  const res = await queryStudentByIdApi(row.id);
  if (res.code) {
    studentForm.value = { ...res.data };
  }
};

const saveStudent = () => {
  studentFormRef.value.validate(async (valid) => {
    if (!valid) return ElMessage.error("表单校验不通过");
    let res;
    if (studentForm.value.id) {
      res = await updateStudentApi(studentForm.value);
    } else {
      res = await addStudentApi(studentForm.value);
    }
    if (res.code) {
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      fetchStudentList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该学员吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteStudentApi(row.id);
      if (res.code) {
        ElMessage.success("删除成功");
        fetchStudentList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 表单校验规则
const rules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  no: [{ required: true, message: "请输入学号", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  idCard: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  isCollege: [{ required: true, message: "请选择是否院校", trigger: "change" }],
  clazzId: [{ required: true, message: "请选择班级", trigger: "change" }],
};
</script>

<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="margin-bottom: 16px">
      <el-form-item label="姓名">
        <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="学号">
        <el-input v-model="searchForm.no" placeholder="请输入学号" clearable />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable>
          <el-option v-for="g in genders" :key="g.value" :label="g.name" :value="g.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级">
        <el-select v-model="searchForm.clazzId" placeholder="请选择班级" clearable>
          <el-option v-for="c in clazzList" :key="c.id" :label="c.name" :value="c.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchStudentList">查询</el-button>
        <el-button @click="clear">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right; margin-left:auto;">
        <el-button type="primary" @click="openAdd">+ 新增学员</el-button>
      </el-form-item>
    </el-form>

    <!-- 学员表格 -->
    <el-table :data="studentList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="no" label="学号" />
      <el-table-column prop="gender" label="性别">
        <template #default="scope">
          {{ genders.find(g => g.value === scope.row.gender)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="clazzId" label="班级">
        <template #default="scope">
          {{ clazzList.find(c => c.id === scope.row.clazzId)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="degree" label="学历">
        <template #default="scope">
          {{ degrees.find(d => d.value === scope.row.degree)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="isCollege" label="是否院校">
        <template #default="scope">
          {{ isCollegeOptions.find(i => i.value === scope.row.isCollege)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="violationCount" label="违纪次数" />
      <el-table-column prop="violationScore" label="违纪扣分" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 16px; text-align: right;"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="studentFormRef?.resetFields()">
      <el-form :model="studentForm" :rules="rules" ref="studentFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="no">
          <el-input v-model="studentForm.no" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="studentForm.gender" placeholder="请选择性别">
            <el-option v-for="g in genders" :key="g.value" :label="g.name" :value="g.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="studentForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="是否院校" prop="isCollege">
          <el-select v-model="studentForm.isCollege" placeholder="请选择是否院校">
            <el-option v-for="i in isCollegeOptions" :key="i.value" :label="i.name" :value="i.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="studentForm.address" placeholder="请输入联系地址" />
        </el-form-item>
        <el-form-item label="学历" prop="degree">
          <el-select v-model="studentForm.degree" placeholder="请选择学历">
            <el-option v-for="d in degrees" :key="d.value" :label="d.name" :value="d.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="毕业时间" prop="graduationDate">
          <el-date-picker v-model="studentForm.graduationDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="班级" prop="clazzId">
          <el-select v-model="studentForm.clazzId" placeholder="请选择班级">
            <el-option v-for="c in clazzList" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudent">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
</style>
